<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\ArchiveItem;

/**
 * ArchiveItemSearch represents the model behind the search form of `backend\models\ArchiveItem`.
 */
class ArchiveItemSearch extends ArchiveItem
{
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'is_Digitized', 'id_section'], 'integer'],
            [['title', 'm_number', 'description'], 'safe'],
        ];
    }

    // public function attributes()
    // {
    //     // делаем поле зависимости доступным для поиска
    //     return array_merge(parent::attributes(), ['section.name']);
    // }


    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = ArchiveItem::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        //$query->joinWith('section sec');

        // $dataProvider->sort->attributes['section.name'] = [
        //     'asc' => ['sec.name' => SORT_ASC],
        //     'desc' => ['sec.name' => SORT_DESC],
        // ];

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'is_Digitized' => $this->is_Digitized,
            'id_section' => $this->id_section,
        ]);

       // $query->andFilterWhere(['like', 'sec.name', $this->getAttribute('section.name')]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'm_number', $this->m_number])
            ->andFilterWhere(['like', 'description', $this->description]);

        return $dataProvider;
    }
}
